<template>
  <div class="bom-container">
    <h2 class="page-title">物料清单</h2>

    <!-- 单据信息卡片 -->
    <el-card class="form-card">
      <el-form :model="form" label-width="120px" label-position="left">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="单据编码：">
              <el-input disabled v-model="form.billCode" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="业务类型：">
              <el-input v-model="form.businessType" value="BOM补料" readonly />
            </el-form-item>
            <el-form-item label="物料编码：">
              <el-input v-model="form.materialCode" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单据日期：">
              <el-date-picker
                v-model="form.billDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="选择日期"
                disabled
              />
            </el-form-item>
            <el-form-item label="操作员：">
              <el-input
                disabled
                v-model="form.operator"
                value="qfman"
                readonly
              />
            </el-form-item>
            <el-form-item disabled label="单据状态：">
              <el-input v-model="form.billStatus" value="开立" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="计划单号：">
              <el-input
                disabled
                v-model="form.planOrderNo"
                placeholder="选择"
              />
            </el-form-item>
            <el-form-item label="销售单号：">
              <el-input v-model="form.salesOrderNo" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="计量单位：">
              <el-input v-model="form.measurementUnit" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="业务状态：">
              <el-select v-model="form.businessStatus">
                <el-option label="正常" value="正常" />
                <el-option label="挂起" value="挂起" />
                <el-option label="手工关闭" value="手工关闭" />
                <el-option label="系统关闭" value="系统关闭" />
              </el-select>
            </el-form-item>
            <el-form-item label="审核员：">
              <el-input disabled v-model="form.auditor" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="订单交期：">
              <el-date-picker
                v-model="form.orderDeliveryDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="选择日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审核日期：">
              <el-date-picker
                v-model="form.auditDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="选择日期"
              />
            </el-form-item>
            <el-form-item label="备注信息：">
              <el-input
                v-model="form.remarks"
                type="textarea"
                placeholder="请输入"
              />
            </el-form-item>
            <el-form-item label="生产数量：">
              <el-input
                v-model="form.productionQuantity"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 物料信息表格 -->
    <el-card class="table-card">
      <div
        style="display: flex; justify-content: flex-end; margin-bottom: 10px"
      >
        <el-button
          type="primary"
          @click="openProductSelector"
          class="action-button"
          >新增产品</el-button
        >
      </div>
      <br />
      <el-table
        @selection-change="handleSelectionChange"
        :data="dialogProductList"
        border
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="index" label="序号" width="60" />
        <el-table-column prop="materialCode" label="物料编码" />
        <el-table-column prop="materialName" label="物料名称">
        </el-table-column>
        <el-table-column prop="modelSpec" label="型号规格" />
        <!-- 修改为正确的属性名 -->
        <el-table-column prop="mainUnit" label="主计量" />
        <!-- 修改为正确的属性名 -->
        <el-table-column prop="demandquantity" label="需求数量">
          <template #default="scope">
            <el-input
              v-model="scope.row.demandquantity"
              placeholder="输入数量"
              type="number"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="available" label="可用量">
          0.00
        </el-table-column>
        <el-table-column prop="received" label="领用量"> 0.00 </el-table-column>
        <el-table-column prop="materialmethod" label="领料方式">
          <template #default="scope">
            <el-select v-model="scope.row.materialmethod" placeholder="请选择">
              <el-option label="按单领用" value="按单领用" />
              <el-option label="定额领用" value="定额领用" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="supplymode" label="供应方式">
          <template #default="scope">
            <el-select v-model="scope.row.supplymode" placeholder="请选择">
              <el-option label="按单说明" value="按单说明" />
              <el-option label="采购" value="采购" />
              <el-option label="自制" value="自制" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button type="danger" link @click="deleteProduct(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <br />
      <div class="table-actions">
        <el-button type="primary" @click="submitForm">修改</el-button>
      </div>
    </el-card>
  </div>
  <el-dialog
    title="选择物料"
    ref="dialogRef"
    v-model="dialogVisible"
    width="1200px"
  >
    <div class="material-select-page">
      <div class="search-bar">
        <el-input
          placeholder="请输入分类名称"
          v-model="searchCategory"
          prefix-icon="el-icon-search"
        ></el-input>
        <el-input placeholder="物料编码" v-model="searchCode"></el-input>
        <el-input placeholder="物料名称" v-model="searchName"></el-input>

        <el-button>连选</el-button>
      </div>
      <div class="main-content">
        <el-table
          @selection-change="handleSelectionChange"
          :data="materials"
          border
          style="width: 800px"
        >
          <el-table-column type="selection"></el-table-column>
          <el-table-column
            prop="materialCode"
            label="物料编码"
            width="180"
          ></el-table-column>
          <!-- 修改为正确的属性名 -->
          <el-table-column
            prop="materialName"
            label="物料名称"
            width="180"
          ></el-table-column>
          <!-- 修改为正确的属性名 -->
          <el-table-column
            prop="modelSpec"
            label="型号规格"
            width="180"
          ></el-table-column>
          <!-- 修改为正确的属性名 -->
          <el-table-column
            prop="mainUnit"
            label="主计量"
            width="120"
          ></el-table-column>
        </el-table>
        <el-pagination
          v-model:current-page="form1.PageIndex"
          v-model:page-size="form1.PageSize"
          :page-sizes="[1, 3, 15, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="form1.TotalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <br />
      <div class="button-group">
        <el-button @click="closeDialog" class="action-button"> 关闭 </el-button>
        <el-button
          type="primary"
          @click="confirmSelection"
          class="action-button"
        >
          选择
        </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ElMessageBox, ElMessage } from "element-plus";
import { reactive, onMounted, ref } from "vue";
import axios from "axios";
import{KongaUrl} from "@/axios/axiosHelp"
import { useRouter, useRoute } from "vue-router";
import dayjs from "dayjs";
const router = useRouter();
const route = useRoute();
const dialogSelection = ref<any[]>([]);
const handleSelectionChange = (val: any[]) => {
  dialogSelection.value = val;
};
const confirmSelection = () => {
  const selectedRows = dialogSelection.value;
  if (selectedRows.length === 0) {
    ElMessage.warning("请选择产品");
    return;
  }
  selectedRows.forEach((selectedProduct) => {
    dialogProductList.value.push({
      materialCode: selectedProduct.materialCode,
      materialName: selectedProduct.materialName,
      modelSpec: selectedProduct.modelSpec,
      mainUnit: selectedProduct.mainUnit,
    });
  });
  closeDialog();
};
const form1 = reactive({
  TotalCount: 0,
  PageCount: 0,
  PageSize: 5,
  PageIndex: 1,
});
const handleSizeChange = (newSize) => {
  form1.PageSize = newSize;
  searchProducts();
};

const handleCurrentChange = (newPage) => {
  form1.PageIndex = newPage;
  searchProducts();
};
// 对话框可见性
const dialogVisible = ref(false);
const closeDialog = () => {
  dialogVisible.value = false;
  dialogProductList.value.forEach((row) => {
    row._checked = false;
  });
};
// 主表单数据
const form = ref({
  billCode: "",
  businessType: "",
  materialCode: "",
  billDate: dayjs().format("YYYY-MM-DD"), // 匹配后端DateTime
  operator: "",
  billStatus: "",
  planOrderNo: "",
  salesOrderNo: "",
  measurementUnit: "",
  businessStatus: "",
  auditor: "",
  orderDeliveryDate: dayjs().format("YYYY-MM-DD"), // 匹配后端DateTime
  auditDate: dayjs().format("YYYY-MM-DD"), // 匹配后端DateTime
  remarks: "",
  productionQuantity: "",
});
const deleteProduct = (product) => {
  ElMessageBox.confirm("确定要删除该产品吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      const index = dialogProductList.value.indexOf(product);
      if (index !== -1) {
        dialogProductList.value.splice(index, 1);
      }
    })
    .catch(() => {});
};
// 物料表格数据
const dialogProductList = ref([]);
const materials = ref([]);
// 搜索条件
const searchCategory = ref("");
const searchCode = ref("");
const searchName = ref("");

// 打开物料选择对话框
const openProductSelector = async () => {
  dialogVisible.value = true;
  searchProducts();
};
const searchProducts = () => {
  KongaUrl
    .get("/wangcong2/api/Log/GetERPMaterials/GetERPMaterials", {
      params: {
        PageSize: form1.PageSize,
        PageIndex: form1.PageIndex,
      },
    })
    .then((res) => {
      materials.value = res.data.data.list;
      form1.TotalCount = res.data.data.totalCount;
      form1.PageCount = res.data.data.PageCount;
    })
    .catch((error) => {
      console.error("获取产品列表失败", error);
    });
};
// 调用后端接口获取物料数据
const submitForm = async () => {
  const requiredFields = [
    "billCode",
    "materialCode",
    "billDate",
    "operator",
    "businessStatus",
  ];
  const missingFields = requiredFields.filter((field) => !form.value[field]);
  if (missingFields.length > 0) {
    ElMessage.error(`以下字段为必填：${missingFields.join(", ")}`);
    return;
  }

  const payload = {
    ...form.value,
    MaterialsBliiId: dialogProductList.value[0]?.materialsBliiId || 0, // 主表ID
    Products: dialogProductList.value.map((item) => ({
      materialCode: item.materialCode,
      demandquantity: Number(item.demandquantity),
      materialName: item.materialName,
      mainUnit: item.mainUnit,
      modelSpec: item.modelSpec,
      supplymode: item.supplymode,
      materialmethod: item.materialmethod,
    })),
  };

  try {
    const res = await KongaUrl.post(
      "/wangcong3/api/Log/UpdateMaterials",
      payload,
      {
        headers: {
          "Content-Type": "application/json", // 明确指定Content-Type
        },
      }
    );
    if (res.data.code === 300) {
      ElMessage.success("修改成功");
      console.log(res.data);
      router.push("/GetProduce");
    } else {
      ElMessage.error(res.data.message);
    }
  } catch (error) {
    ElMessage.error("请求失败，请检查控制台");
    console.error("API Error:", error);
  }
};
const generateTwelveDigitNumber = () => {
  const characters = "0123456789";
  let result = "";
  for (let i = 0; i < 12; i++) {
    // 生成12位数字
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return result;
};
const handleView = () => {
  const sellStringCode = route.query.materialCode; // 改为通过销售单号查询

  if (!sellStringCode) {
    console.log("未获取到销售单号");
    return;
  }

  // 统一使用form.value来管理表单数据
  form.value.materialCode = sellStringCode as string;

  // 获取入库单基本信息
  KongaUrl
    .get(`/wangcong2/api/Log/EditBillInfo`, {
      params: {
        MaterialCode: sellStringCode, // 确保后端API接收这个参数
      },
    })
    .then((res) => {
      if (res.data.data && res.data.data.length > 0) {
        const basicInfo = res.data.data[0];
        Object.assign(form.value, {
          ...basicInfo,
        });
      }
    });

  // 获取产品信息
  KongaUrl
    .get(`/wangcong2/api/Log/EditMaterialsBlii`, {
      params: {
        MaterialCode: sellStringCode, // 确保后端API改为通过销售单号查询
      },
    })
    .then((res) => {
      dialogProductList.value = res.data.data.map((item) => ({
        materialsBliiId: item.materialsBliiId,
        materialCode: (route.query.materialCode as string) || "",
        demandquantity: Number(item.demandquantity),
        materialName: item.materialName,
        mainUnit: item.mainUnit,
        modelSpec: item.modelSpec,
        supplymode: item.supplymode,
        materialmethod: item.materialmethod,
      }));
    });
};
onMounted(() => {
  handleView();
});
</script>

<style scoped>
.material-select-page {
  padding: 10px;
}
.search-bar {
  margin-bottom: 10px;
  display: flex;
  gap: 10px;
}
.main-content {
  display: flex;
  gap: 10px;
}
.left-menu {
  width: 200px;
}
.bom-container {
  padding: 20px;
}
.page-title {
  margin-bottom: 20px;
  color: #333;
}
.form-card {
  margin-bottom: 20px;
}
.table-actions {
  margin-top: 20px;
  text-align: right;
}
.el-select {
  width: 100%;
}
.el-table {
  margin-top: 20px;
}
.material-select-container {
  padding: 20px;
}
.search-card {
  margin-bottom: 20px;
}
.search-card .el-col {
  margin-bottom: 10px;
}
.table-card {
  margin-top: 20px;
}
.el-button + .el-button {
  margin-left: 10px;
}
.el-table__empty-block {
  min-height: 200px;
}
.el-loading-spinner {
  top: 40%;
}
</style>